import Taro, { Component } from '@tarojs/taro'
import { AtTabs, AtTabsPane } from 'taro-ui'
import { View, ScrollView, Button } from '@tarojs/components'
import { DNavBar, DCarship, DItemError, DModal, DPaymodel } from '@/components'
import http from '@/api'
import './consignment.scss'
import sdk from '@/common/sdk'
const getUrlScheme = http.getUrlScheme
export default class consignment extends Component {
  constructor(props) {
    super(props)
    this.state = {
      active: 0,
      page: 1,
      limit: 10,
      totalPage: 1,
      list: [],
      footerStatus: false,
      ispayShow: false,
      firstList: [],
      secondList: [],
      threeList: [],
      foundList: [],
      fiveList: [],
      isShow: false,
      id: '',
      scrollHeight: window.screen.availHeight,
      listStatus: false
    }
  }

  componentWillMount() {
    let { active = 1 } = this.$router.params
    this.handleClick(+active)
    if (window.localStorage.getItem('ISPAY')) {
      // this.state.isOpened： = true
      this.setState({
        isOpened: true
      }, () => window.localStorage.removeItem('ISPAY'))
    }
    // this.setState({
    //   active:+active-1
    // })
    // this.getListInfo(+active)
  }

  componentDidShow() {
    let { listStatus } = this.state
    if (listStatus) {
      return
    }
    this.setState({
      list: [],
      footerStatus: false,
      page: 1,
      limit: 10,
      totalPage: 1,
      listStatus: true
    }, () => {
      this.getListInfo()
    })
    sdk.setTitleInfo('托运订单')
  }

  getStatusText(status) {
    return {
      $11: "待支付",
      $21: "待承运方接单",
      $31: "待承运方上传",
      $32: "待确认",
      $41: "待承运方上传",
      $42: "待确认",
      $43: "待核实",
      $51: "交易成功",
      $52: "已拒接",
      $53: "已撤回",
      $54: "已超时",
      $55: "交易异常",
      $59: "待卖家同意退款",
    }[`$${status}`]
  }

  getFirstText(active) {
    return {
      $11: "支付费用",
      $21: "撤回订单",
      $32: "确认验车",
      $42: "确认合同"
    }[`$${active}`]
  }
  getListInfo(act) {
    let { active, page, limit, totalPage } = this.state
    let _obj = {
      page,
      limit,
      status: act ? act : active + 1
    }
    if (page > totalPage) {
      this.setState({
        footerStatus: true
      })
      return
    }
    http.getListTrans(_obj).then(res => {
      let list = []
      if (res.list && res.list.length > 0) {
        let data = res.list
        if (active === 0) {
          // 将待支付中超时的筛选掉
          data = data.filter(item => item.orStatus != 54)
        }
        data.map((item, i) => {
          list.push({
            id: item.id,
            order: item.orNo,
            card: item.cdCarType.split('#')[0],
            addre: item.orSaleComp,
            data: item.createTime.split(' ')[0],
            title: this.getStatusText(item.orStatus),
            beginaddre: item.cdStartAddr,
            endaddre: item.cdEndAddr,
            money: item.orPrice,
            orStatus: item.orStatus,
            firstText: this.getFirstText(item.orStatus) || '查看订单'
          })
        })
      }
      totalPage = res.totalPage

      this.setState({
        list: [...this.state.list, ...list],
        totalPage,
        listStatus: false
      })
    })
  }

  handleClick(value) {
    this.setState({
      list: [],
      footerStatus: false,
      active: value,
      page: 1,
      limit: 10,
      totalPage: 1,
      listStatus: true
    }, () => {
      this.getListInfo()
    })
  }

  onScrollEnd = () => {
    this.setState({
      page: this.state.page + 1
    }, () => {
      this.getListInfo()
    })
  }

  onHandleDetail(item) {
    Taro.navigateTo({
      url: `/pages/itemdetail/itemdetail?id=${item.id}&status=${item.orStatus}`
    })
  }
  handleClose() {
    this.setState({
      ispayShow: false
    })
  }
  //支付订金
  onhandlePay(item) {
    // alert('支付订金')

    this.setState({
      ispayShow: true,
      indList: item || {}
    })
  }
  async onCancelPay(payType = '1') {
    let { indList } = this.state
    if (payType == 8) {
      const urlScheme = await getUrlScheme(indList.id, 0)
      window.location.href = urlScheme
      return
    }
    http.transPayOrder({ id: indList.id, payIp: window.payIp, payType }).then(res => {
      setTimeout(() => {
        // Taro.navigateBack({
        //     delta: 2
        // })
        // Taro.redirectTo({
        //     url: `/pages/consignment/consignment?active=1`
        // })
        if (+payType === 1) {
          window.localStorage.setItem('ISPAY', 1)
        }
        if (!res) {
          return Taro.showToast({
            title: '订单状态异常',
            icon: 'none'
          })
        }
        if (payType == 7) {
          let url = encodeURIComponent(res)
          return Taro.navigateTo({
            url: `/pages/wxQrCode?payUrl=(${encodeURI(url)})`
          })
        }
        window.location.href = res
      }, 1000)
    })
  }
  payFuc(type) {
    let act = 0
    this.setState({
      isOpened: false,
    })
    if (type) {
      act = 1
    }
    Taro.redirectTo({
      url: `/pages/shoporders/shoporders?active=${act}`
    })
  }
  onHandleFirst(item) {
    this.setState({
      id: item.id
    })
    if (item.firstText === '支付费用') {
      this.onhandlePay(item)
    }
    else if (item.firstText === '撤回订单') {
      this.setState({
        isShow: true
      })
    }
    else if (item.firstText === '确认验车') {
      Taro.navigateTo({
        url: `/pages/checkimg/checkimg?id=${item.id}&status=1`
      })
    }
    else if (item.firstText === '确认合同') {
      http.buyersConfirm3(item.id).then(res => {
        if (res === 0) {
          Taro.showToast({
            title: '该合同已确认',
            icon: 'none',
            duration: 800
          })
          setTimeout(() => {
            window.location.reload()
          }, 800);
        } else {
          Taro.navigateTo({
            url: `/pages/contractprooftran/contractprooftran?id=${item.id}&status=1`
          })
        }
      })
    }
    else if (item.firstText === '查看订单') {
      Taro.navigateTo({
        url: `/pages/itemdetail/itemdetail?id=${item.id}&status=${item.orStatus}`
      })
    }
  }
  //撤回订单
  getBackOrder(id) {
    http.getBackOrder2({ id }).then(res => {
      Taro.navigateTo({
        url: `/pages/itemdetail/itemdetail?id=${id}&status=53`
      })
    })
  }
  onClose() {
    this.setState({
      isShow: false
    })
  }
  onLastHandle() {
    let { id } = this.state
    this.onClose()
    this.getBackOrder(id)
  }

  render() {
    const tabList = [{ title: '待支付' }, { title: '待接单' }, { title: '待验车' }, { title: '确认合同' }, { title: '已完结' }]
    const {
      active,
      list,
      footerStatus,
      scrollHeight,
      isShow
    } = this.state
    return (
      <View className='b_consignment'>
        <DNavBar title={'托运订单'} className='b_consignment_nav'></DNavBar>
        <View className='b_consignment__box'>
          <View className='b_consignment__content'>
            <AtTabs current={active} tabList={tabList} onClick={this.handleClick.bind(this)}>
              {
                tabList.map(tap => <AtTabsPane>
                  <ScrollView
                    scrollY
                    scrollWithAnimation
                    lowerThreshold='20'
                    style={`height:${scrollHeight - 100}PX`}
                    onScrollToLower={this.onScrollEnd}
                  >
                    {
                      list && list.map((item, i) => {
                        return <DCarship
                          onHandleDetail={this.onHandleDetail.bind(this, item)}
                          {...item}
                          status={item.title}
                          onHandleFirst={this.onHandleFirst.bind(this, item)}
                        >
                        </DCarship>
                      })
                    }
                    {
                      footerStatus && <View className='b_consignment__more'>暂无更多</View>
                    }
                  </ScrollView>
                </AtTabsPane>
                )
              }
            </AtTabs>
          </View>
        </View>
        {
          list.length === 0 && <DItemError></DItemError>
        }
        <DModal
          isShow={isShow}
          title='提示'
          text='确认撤回订单吗？'
          firstbtn='取消'
          lastbtn='确认'
          onFirst={this.onClose.bind(this)}
          onCancel={this.onClose.bind(this)}
          onLast={this.onLastHandle.bind(this)}
        ></DModal>
        <DPaymodel handleClose={this.handleClose.bind(this)} onCancel={this.onCancelPay.bind(this)} isShow={this.state.ispayShow} />
      </View>

    )
  }
}
